package org.example.commons;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.MDC;

import java.io.Serializable;

@Data
@NoArgsConstructor
public class ApiResponse<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    // code
    private int code;

    // message
    private String message;

    // 数据
    private T data;

    private String traceId;

    public ApiResponse(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.traceId = MDC.get("traceId");
    }

    public ApiResponse(int code, String message) {
        this.code = code;
        this.message = message;
        this.traceId = MDC.get("traceId");
    }

    public static <T> ApiResponse<T> success() {
        return new ApiResponse<T>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage());
    }

    public static <T> ApiResponse<T> success(T data) {
        return new ApiResponse<T>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), data);
    }

    public static <T> ApiResponse<T> error() {
        return new ApiResponse<T>(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getMessage());
    }

    public static <T> ApiResponse<T> error(String message) {
        return new ApiResponse<T>(ResponseCode.ERROR.getCode(), message);
    }
}
